#include "language.h"
#include "ui_language.h"
#include "introduction.h"
#include "unistd.h"
#include "main.h"

language::language(QTranslator *translator, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::language),
    translator(translator)
{
    ui->setupUi(this);
    this->setWindowIcon(QIcon(":/resourceFile/xin.ico"));
    this->setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint);
    this->setWindowTitle(tr("安装语言"));
    ui->labelSelectLanguage->setText(tr("请选择语言"));
    ui->labelIco->setPixmap(QPixmap(":/resourceFile/xin.ico"));
    ui->labelIco->setScaledContents(true); //自适应
    ui->pushButtonOK->setText(tr("确定"));
    ui->pushButtonCancel->setText(tr("取消"));
    ui->comboBoxLanguage->addItem(tr("简体中文"));
    ui->comboBoxLanguage->addItem(tr("English"));
    connect(ui->pushButtonOK, SIGNAL(clicked(bool)), this, SLOT(buttonOK()));
    connect(ui->pushButtonCancel, SIGNAL(clicked(bool)), this, SLOT(buttonCancel()));
}

language::~language()
{
    delete ui;
}

void language::closeEvent(QCloseEvent *event)
{
    QMessageBox* box = new QMessageBox(QMessageBox::Question, tr("%1 %2的安装").arg(xin::exeName).arg(xin::versions) ,
                                       tr("你确定要退出%1 %2 的安装吗?").arg(xin::exeName).arg(xin::versions),
                                       QMessageBox::Yes | QMessageBox::No);

    box->button(QMessageBox::Yes)->setText(tr("是"));
    box->button(QMessageBox::No)->setText(tr("否"));
    box->button(QMessageBox::No)->setFocus(); //设置焦点
    //此move会有变动
    box->move(this->x() + (((this->width() - 310) / 2)), this->y() + ((this->height() - 120) / 2));
    int ret = box->exec();
    if (ret != QMessageBox::Yes) {
        event->ignore();
    }
}

void language::buttonOK()
{
    Introduction* introduction;
    QString languageQm;
    switch (ui->comboBoxLanguage->currentIndex()) {
    case xin::simplifiedChinese:
        languageQm = ":/resourceFile/Chinese.qm";
        break;
    case xin::English:
        languageQm = ":/resourceFile/English.qm";
        break;
    default:
        break;
    }
    translator->load(languageQm);
    isInstall(); //检测是否安装
#if defined (Q_OS_LINUX)
#else
    exeIsStart(); //检测是否启动
#endif

    introduction = new Introduction();
    QDesktopWidget* desktop = QApplication::desktop(); // =qApp->desktop();也可以
    introduction->move((desktop->width() - introduction->width())/2, (desktop->height() - introduction->height())/2);
    introduction->show();
    this->hide();
}

void language::buttonCancel()
{
    QMessageBox* box = new QMessageBox(QMessageBox::Question, tr("%1 %2的安装").arg(xin::exeName).arg(xin::versions) ,
                                       tr("你确定要退出%1 %2 的安装吗?").arg(xin::exeName).arg(xin::versions),
                                       QMessageBox::Yes | QMessageBox::No);

    box->button(QMessageBox::Yes)->setText(tr("是"));
    box->button(QMessageBox::No)->setText(tr("否"));
    box->button(QMessageBox::No)->setFocus(); //设置焦点
    //此move会有变动
    box->move(this->x() + (((this->width() - 310) / 2)), this->y() + ((this->height() - 120) / 2));
    int ret = box->exec();
    if (ret == QMessageBox::Yes) {
        exit(1);
    }
}


void language::exeIsStart()
{
    process = new QProcess;
    process->start("tasklist");
    process->waitForFinished();
    QString outputStr = QString::fromLocal8Bit(process->readAllStandardOutput());
    if (outputStr.contains(xin::exeName + ".exe")) {
        QMessageBox* box = new QMessageBox(QMessageBox::Question, tr("%1 %2的安装").arg(xin::exeName).arg(xin::versions) ,
                                           tr("您的%1正在运行\n请问是否关闭立即安装?").arg(xin::exeName),
                                           QMessageBox::Yes | QMessageBox::No);

        box->button(QMessageBox::Yes)->setText(tr("立即安装"));
        box->button(QMessageBox::No)->setText(tr("下次再说"));
        //此move会有变动
        box->move(this->x() + (((this->width() - 310) / 2)), this->y() + ((this->height() - 120) / 2));
        int ret = box->exec();
        if (ret == QMessageBox::Yes) {
            QProcess p;
            p.execute("taskkill /f /t /im " + xin::executableExeName); //要使用socket的方式杀死
        }
        else {
            exit(1);
        }
    }
}

void language::isInstall()
{
    QSettings* settingsVersions;
#if defined (Q_OS_LINUX)
    settingsVersions = new QSettings(xin::exeName + "Versions", xin::exeName);
#else
    settingsVersions = new QSettings(QString("HKEY_CLASSES_ROOT\\%1Versions").arg(xin::exeName), QSettings::NativeFormat);
#endif
    if (settingsVersions->contains("Versions")) {
        QString oldVersions = settingsVersions->value("Versions").toString();
        oldVersions.remove('.'); //剔除版本号的特殊字符
        QString newVersions = xin::versions;
        newVersions.remove('.');
        if (newVersions.toInt() > oldVersions.toInt()) {
            QMessageBox* box = new QMessageBox(QMessageBox::Question, tr("%1 %2的安装").arg(xin::exeName).arg(xin::versions) ,
                                               tr("检测到当前%1的版本较新,\n请问是否替换当前旧版本?").arg(xin::exeName),
                                               QMessageBox::Yes | QMessageBox::No);

            box->button(QMessageBox::Yes)->setText(tr("是"));
            box->button(QMessageBox::No)->setText(tr("否"));
            box->button(QMessageBox::Yes)->setFocus(); //设置焦点
            //此move会有变动
            box->move(this->x() + (((this->width() - 310) / 2)), this->y() + ((this->height() - 120) / 2));
            int ret = box->exec();
            if (ret == QMessageBox::Yes) {
                return;
            }
            else {
                exit(1);
            }
        }
        if (newVersions.toInt() == oldVersions.toInt()) {
            QMessageBox* box = new QMessageBox(QMessageBox::Question, tr("%1 %2的安装").arg(xin::exeName).arg(xin::versions) ,
                                               tr("检测到当前%1的版本相同,\n请问是否继续安装?").arg(xin::exeName),
                                               QMessageBox::Yes | QMessageBox::No);

            box->button(QMessageBox::Yes)->setText(tr("是"));
            box->button(QMessageBox::No)->setText(tr("否"));
            box->button(QMessageBox::No)->setFocus(); //设置焦点
            //此move会有变动
            box->move(this->x() + (((this->width() - 310) / 2)), this->y() + ((this->height() - 120) / 2));
            int ret = box->exec();
            if (ret == QMessageBox::Yes) {
                return;
            }
            else {
                exit(1);
            }
        }
        if (newVersions.toInt() < oldVersions.toInt()) {
            QMessageBox* box = new QMessageBox(QMessageBox::Question, tr("%1 %2的安装").arg(xin::exeName).arg(xin::versions) ,
                                               tr("检测到当前%1的版本较旧,\n请问是否替换当前新版本?").arg(xin::exeName),
                                               QMessageBox::Yes | QMessageBox::No);

            box->button(QMessageBox::Yes)->setText(tr("是"));
            box->button(QMessageBox::No)->setText(tr("否"));
            box->button(QMessageBox::Yes)->setFocus(); //设置焦点
            //此move会有变动
            box->move(this->x() + (((this->width() - 310) / 2)), this->y() + ((this->height() - 120) / 2));
            int ret = box->exec();
            if (ret == QMessageBox::Yes) {
                return;
            }
            else {
                exit(1);
            }
        }
    }
}



int entry(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QFile file(":/resourceFile/ui.qss");
    if (file.open(QIODevice::ReadOnly)) {
        a.setStyleSheet(file.readAll());
        file.close();
    }
#if defined (Q_OS_LINUX)
    __uid_t id = getuid();
    int uid = id;
    qint64 pid = QCoreApplication::applicationPid();


    QString newExeName = QCoreApplication::applicationName();
    QProcess* exeLsit = new QProcess;
    exeLsit->start("ps -ef");
    exeLsit->waitForFinished();
    QString psData = QString::fromLocal8Bit(exeLsit->readAll());
    int count = psData.count(newExeName);
    count--;
    if (count > 1 && uid != 0) {
        exit(0);
    }
    //此判断用于再次启动后为了下面 创建文件夹保证和上一个程序的判断文件夹名相等！
    if (argc >= 2) {
        QString temp = argv[1];
        pid = temp.toLongLong();
    }
    qDebug() << "uid=" << uid;
    qDebug() << "newExeName=" << newExeName;
    qDebug() << "count=" << count;
    qDebug() << "pid=" << pid;
    //每次根据pid创建
    QString mkdirPath = ".QWERZDFASHGFXZASRwqeasd" + QString::number(pid);
    QDir d("/usr");
    d.rmdir(mkdirPath);
    //普通用户运行删除和创建都失败那么就进入else,热如果是root直接打开窗口
    if (d.mkdir(mkdirPath)) {
        QThread::msleep(1000);
        //d.rmdir("/usr/" + mkdirPath);
        language* w = new language;
        QDesktopWidget* desktop = QApplication::desktop(); // =qApp->desktop();也可以
        w->move((desktop->width() - w->width())/2, (desktop->height() - w->height())/2);
        w->show();
    }
    else {
        //从linux下proc获取进程绝对路径
        QString path = "/proc/" + QString::number(QCoreApplication::applicationPid()) + "/cmdline";
        QFile f(path);
        QString appPath;
        if (f.open(QIODevice::ReadOnly)) {
            //appPath = f.readAll();//如果是appimagetool制作的程序那么使用下面的获取路径会不准
            appPath = QCoreApplication::applicationFilePath();//自测,用于非appimagetool制作程序
        }
        else {
            QMessageBox msgBox;
            msgBox.setText("读取失败");
            msgBox.exec();
        }
        QThread::msleep(500);
        QString passwordError;
        int num = 0;
        while (!QDir("/usr/" + mkdirPath).exists()) {
            QStringList args;
            QProcess* ps = new QProcess;
            if (num >= 3) {
                QMessageBox::warning(0,"密码错误次数过多", "请使用root权限启动");
                exit(0);
            }
            QString text = "";
            if (passwordError.isEmpty()) {
                QInputDialog* input = new QInputDialog;
                input->resize(300, 300);
                input->setWindowTitle("在安装前请先进行程序授权!");
                input->setLabelText("输入密码");
                input->setTextEchoMode(QLineEdit::Password);
                input->exec();
                text = input->textValue();
            }
            else {
                QInputDialog* input = new QInputDialog;
                input->resize(410, 300);
                input->setWindowTitle(passwordError);
                input->setLabelText("输入密码");
                input->setTextEchoMode(QLineEdit::Password);
                input->exec();
                text = input->textValue();
            }
            if (!text.isEmpty()) {
                args.clear();
                args << "-c";
                args << "echo '" + text + "'" + " | sudo -S " + appPath + QString(" %1").arg(pid);
                qDebug() << args;
                ps->start("/bin/bash", args); // /bin/bash
                ps->waitForFinished(1000);
            }
            else {
                exit(0);
            }
            num++;
            passwordError = "密码错误"  + QString::number(num) + "次,请重新输入密码,或者以root权限启动程序";
        }
        exit(0);
    }
#else
    bool isDetectionTwoStart = true;
    if (argc >= 2) { //用于失败重新安装，允许前者未退出，后者可启动，但是需要带参启动验证，证明是失败重新安装
        QString temp = argv[1];
        if (temp == "666666") {
            isDetectionTwoStart = false; //取消检测二次启动
        }
    }
    if (isDetectionTwoStart) {
        QSharedMemory shared;
        shared.setKey("Xin");
        if (shared.attach()) {
            QMessageBox msgBox;
            msgBox.setText("已有一个安装程序启动,请勿重复启动");
            msgBox.exec();
            exit(0);
        }
        shared.create(1);
    }


    QTranslator translator;
    qDebug() <<  translator.load(":/resourceFile/Chinese.qm");
    a.installTranslator(&translator);


    language* w = new language(&translator);
    QDesktopWidget* desktop = QApplication::desktop(); // =qApp->desktop();也可以
    w->move((desktop->width() - w->width())/2, (desktop->height() - w->height())/2);
    w->show();
#endif
    return a.exec();
}
